package cn.yaoud.salus.oms.alarm.autoconfigure;

import cn.yaoud.salus.oms.alarm.Alerter;
import cn.yaoud.salus.oms.alarm.advice.NoticeExceptionAdvice;
import cn.yaoud.salus.oms.alarm.feishu.FeiShuAlerter;
import cn.yaoud.salus.oms.alarm.feishu.bot.FeiShuCustomRobotProperties;
import cn.yaoud.salus.oms.alarm.util.DiscardWithReport;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * 告警通知组件自动配置类
 *
 * @author 唐彪
 */

@Configuration
@EnableConfigurationProperties({OmsAlarmProperties.class, FeiShuCustomRobotProperties.class})
@ConditionalOnClass(OmsAlarmProperties.class)
@ConditionalOnProperty(prefix = "oms-alarm", name = "enabled", havingValue = "true", matchIfMissing = true)
public class OmsAlarmAutoConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;
    @Resource
    private OmsAlarmProperties omsAlarmProperties;

    @Bean(name = "noticeExceptionExecutor")
    public Executor noticeExceptionExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setQueueCapacity(Integer.parseInt("1000"));
        executor.setRejectedExecutionHandler(new DiscardWithReport());
        executor.setThreadNamePrefix("notice-exception-");
        return executor;
    }

    @Bean
    public NoticeExceptionAdvice noticeExceptionAdvice(Alerter feiShuAlarm) {
        NoticeExceptionAdvice advice = new NoticeExceptionAdvice();
        advice.setAlerter(feiShuAlarm);
        advice.setOmsAlarmProperties(omsAlarmProperties);
        return advice;
    }

    @Bean
    public Alerter feiShuAlarm(@Qualifier("noticeExceptionExecutor") Executor noticeExceptionExecutor) {
        FeiShuAlerter alerter = new FeiShuAlerter();
        alerter.setApplicationName(applicationName);
        alerter.setExecutor(noticeExceptionExecutor);
        return alerter;
    }
}
